package com.turtle.security.security.service;

import com.turtle.security.common.exception.CustomException;
import com.turtle.security.organizates.entity.SysUser;
import com.turtle.security.organizates.service.impl.SysUserServiceImpl;
import com.turtle.security.security.dto.AuthUserDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

/**
 * 自定义的用户详情
 *
 * @author turtle
 * date: 2020-05-11
 */
@Service
@AllArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class CustomerUserDetailsService implements UserDetailsService {
    private final SysUserServiceImpl userService;

    @Override
    public UserDetails loadUserByUsername(String username) {

        // 通过账号获取用户信息
        SysUser user = userService.getUserByUsername(username);
        if (user == null) {
            log.error("登录账号" + username + "不存在");
            throw new CustomException("登录账号" + username + "不存在");
        }
        AuthUserDTO authUser = new AuthUserDTO();
        authUser.setUserId(user.getUserId());
        authUser.setUserName(user.getUserName());
        authUser.setPassword(user.getPassword());
        return authUser;
    }
}
